package org.ifilm.service;

import org.ifilm.dao.UserDao;

import org.ifilm.model.UserRating;
import org.ifilm.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * User Service implementation
 * 
 * @author Mustafa Genc
 *
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	
	@Override
	public User createUser(User user) {
		return userDao.createUser(user);
	}

	@Override
	public User getUser(String email, String password) {
		return userDao.getUser(email, password);
	}
	
	@Override
	public void editUser(User user){
		userDao.editUser(user);
	}

	@Override
	public User getUserById(Long id) {
		return userDao.getUserById(id);
	}
	
	@Override
	public void rateUser(UserRating userRating) {
		userDao.createUserRating(userRating);
		
		User ratedUser = userRating.getRatedUser();
		
		Double oldTotalAvgRate = (double) (ratedUser.getAverageRate() * ratedUser.getTotalRate());
		
		ratedUser.setTotalRate(ratedUser.getTotalRate() + 1);
		
		Float newAvgRate = (float) ((oldTotalAvgRate + userRating.getRate()) / ratedUser.getTotalRate());
		ratedUser.setAverageRate(newAvgRate);
	}

	@Override
	public UserRating getUserRate(Long userId, User rater) {
		return userDao.getUserRate(userId, rater);
	}

	@Override
	public void updateRate(User user, UserRating oldRating, Integer newRate) {
		Double oldTotalAvgRate = (double) (user.getAverageRate() * user.getTotalRate());
		
		Float newAvgRate = (float) ((oldTotalAvgRate - oldRating.getRate() + newRate) / user.getTotalRate());
		user.setAverageRate(newAvgRate);
		
		oldRating.setRate(newRate);
	}

	@Override
	public void followUser(User followerUser, User followingUser) {
		followerUser.getFollowingUsers().add(followingUser);
		followerUser.setFollowingUsers(followerUser.getFollowingUsers());
	}

	@Override
	public void unfollowUser(User followerUser, User followingUser) {
		followerUser.getFollowingUsers().remove(followingUser);
	}
}